<template>
  <div class="home">
    <!-- 主要内容区域 -->
    <div class="main-container">
      <div class="container">
        <!-- 轮播图区域 -->
        <section class="banner-section">
          <BannerCarousel v-if="banners.length > 0" :banners="banners" :height="carouselHeight"/>
        </section>

        <!-- 热门分类 -->
        <section v-if="hotCategories.length > 0" class="category-section">
          <div class="section-header">
            <h2 class="section-title">熱門產品</h2>
          </div>
          <div class="category-grid">
            <div
                v-for="category in hotCategories"
                :key="category.id"
                class="category-item"
                @click="$router.push(`/product/${category.id}`)"
            >
              <div class="category-image">
                <img :src="category.image" :alt="category.name"/>
              </div>
              <div class="category-info">
                <el-tooltip :content="category.name" placement="top">
                  <h3 class="category-name">{{ category.name }}</h3>
                </el-tooltip>
                <span style="color: var(--primary-color);font-weight: bold;font-size: large"><Currency/>{{
                    formatPrice(category.price)
                  }}</span>
              </div>
            </div>
          </div>
        </section>

        <!-- 推荐產品 -->
        <section class="products-section">
          <div class="section-header">
            <h2 class="section-title">爲你推薦</h2>
          </div>

          <div v-loading="loading" class="products-grid">
            <div
                v-for="product in displayProducts"
                :key="product.id"
                class="product-card"
                @click="$router.push(`/product/${product.id}`)"
            >
              <div class="product-image">
                <img :src="product.image" :alt="product.name"/>
                <div class="product-tags">
                  <span v-if="product.sales > 5" class="product-tag hot">熱銷</span>
                  <span v-if="product.reviewCount > 20" class="product-tag popular">热门</span>
                </div>
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <div class="product-meta">
                  <div class="product-rating">
                    <el-rate
                        :model-value="product.rating / 2"
                        disabled
                        size="small"
                        show-score
                        text-color="#ff9900"
                        :score-template="`${product.rating}`"
                    />
                    <span class="review-count">({{ product.reviewCount }})</span>
                  </div>
                  <div class="product-sales">已售{{ product.sales }}件</div>
                </div>
                <div class="product-price">
                  <span class="current-price"><Currency/>{{ formatPrice(product.price) }}</span>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- 促销活动 -->
        <section class="promotion-section">


          <div class="random-products-list">
            <h2 v-if="recommend.length > 0" style="color: #d1d1d1">精選產品</h2>
            <div
                v-for="product in recommend"
                :key="product.id"
                class="random-product-item"
                @click="$router.push(`/product/${product.id}`)"
            >
              <div class="random-product-image">
                <img :src="product.image" :alt="product.name"/>
              </div>
              <div class="random-product-info">
                <h4 class="random-product-name">{{ product.name }}</h4>

                <div class="random-product-price">
                  <span class="random-current-price"><Currency/>{{ formatPrice(product.price) }}</span>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, onUnmounted, ref} from 'vue'
import BannerCarousel from '@/components/common/BannerCarousel.vue'
import {fetchBanner, fetchHomeData, fetchHot, fetchRan, fetchRecommend} from "@/request/req.ts";
import {commonStore} from '@/store/common.ts'
import {formatPrice} from '@/utils/formatPrice'
import Currency from "@/components/common/Currency.vue";

const common = commonStore()

const displayProducts = ref<any[]>([])
const banners = ref([])
const loading = ref(false)
const randomProducts = ref<any[]>([])
const countdown = ref({
  days: '01',
  hours: '00',
  minutes: '00',
  seconds: '00'
})

const serverUrl = computed(() => {
  const item = common.getItemById(1)
  return item?.value
})

// 响应式轮播图高度
const windowWidth = ref(window.innerWidth)
const carouselHeight = computed(() => {
  if (windowWidth.value >= 1200) {
    return '600px'
  } else if (windowWidth.value >= 992) {
    return '500px'
  } else if (windowWidth.value >= 768) {
    return '400px'
  } else {
    return '200px'
  }
})
const updateWindowWidth = () => {
  windowWidth.value = window.innerWidth
}

const getFetchBanner = async () => {
  const res = await fetchBanner()
  banners.value = res.SlidesList.map((item: any) => ({
    id: item.Id,
    image: `${serverUrl.value}/images/Slides/${item.PicName}`,
    type: item.Type
  }))
}
//获取首页数据
const getHomeData = async () => {
  const res = await fetchHomeData(6)
  if (res && res.GoodsList) {
    displayProducts.value = await res.GoodsList.map((item: any) => ({
      id: item.Id,
      name: item.GoodsName,
      price: item.Pirce,
      originalPrice: item.Pirces,
      image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
      description: item.ProductDescription,
      rating: item.StarCount,
      reviewCount: item.Views || 0,
      sales: item.SalesVolume || 0,
      tags: []
    }));
  }
}

interface Category {
  id: number;
  name: string;
  price: number;
  image: string;
  description: string;
}

// 推荐分类
const hotCategories = ref<Category[]>([])

//精选商品
interface recommend {
  id: number;
  name: string;
  price: number;
  image: string;
  Pirce: number;
  description: string;
}

//精选
const recommend = ref<recommend[]>([])

interface promotion {
  id: number;
  name: string;
  image: string;
  description: string;
  price: number;
}

/**
 * 精选
 */
const featuredProducts = async () => {
  const res = await fetchRecommend(6)
  return recommend.value = res.GoodsList.map((item: any) => ({
    id: item.Id,
    name: item.GoodsName,
    price: item.Pirce,
    originalPrice: item.Pirces,
    image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
    description: item.ProductDescription,
    rating: item.StarCount,
    reviewCount: item.Views || 0,
  }))
}

interface promotion {
  id: number;
  name: string;
  image: string;
  description: string;
  price: number;
}

// 促销活动
const promotions = ref<promotion[]>([])

let countdownTimer: number | null = null


/**
 * 推荐產品
 */
const loadFetchHot = async () => {
  const res = await fetchHot(4)
  hotCategories.value = await res.GoodsList.map((item: any) => ({
    id: item.Id,
    name: item.GoodsName,
    price: item.Pirce,
    originalPrice: item.Pirces,
    image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
    description: item.ProductDescription,
    rating: item.StarCount / 2,
    reviewCount: item.Views || 0,
    sales: item.SalesVolume || 0,
  }))
}

/**
 * 获取随机產品
 */
const loadRandomProducts = async () => {
  const res = await fetchRan({id: 4})
  // hotCategories.value = res.GoodsList.map((item: any) => ({
  //   id: item.Id,
  //   name: item.GoodsName,
  //   price: item.Pirce,
  //   originalPrice: item.Pirces,
  //   image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
  //   description: item.ProductDescription,
  //   rating: item.StarCount / 2,
  //   reviewCount: item.Views || 0,
  //   sales: item.SalesVolume || 0,
  //   tags: []
  // }));

  promotions.value = res.GoodsList.map((item: any) => ({
    id: item.Id,
    name: item.GoodsName,
    price: item.Pirce,
    image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
    description: item.ProductDescription
  }));


  randomProducts.value = res.GoodsList.map((item: any) => ({
    id: item.Id,
    name: item.GoodsName,
    price: item.Pirce,
    originalPrice: item.Pirces,
    image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
    description: item.ProductDescription,
    rating: item.StarCount / 2,
    reviewCount: item.Views || 0,
    sales: item.SalesVolume || 0,
    specs: item.Format || ''
  }));
}

const promotionEndTime = ref(new Date().getTime() + 24 * 60 * 60 * 1000)

// 更新倒计时
const updateCountdown = () => {
  const now = new Date().getTime()
  const distance = promotionEndTime.value - now

  if (distance > 0) {
    const days = Math.floor(distance / (1000 * 60 * 60 * 24))
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((distance % (1000 * 60)) / 1000)

    countdown.value = {
      days: days.toString().padStart(2, '0'),
      hours: hours.toString().padStart(2, '0'),
      minutes: minutes.toString().padStart(2, '0'),
      seconds: seconds.toString().padStart(2, '0')
    }
  } else {
    promotionEndTime.value = new Date().getTime() + 24 * 60 * 60 * 1000
    countdown.value = {
      days: '01',
      hours: '00',
      minutes: '00',
      seconds: '00'
    }
  }
}

onMounted(() => {
  featuredProducts()
  getFetchBanner()
  loadFetchHot()
  loadRandomProducts()
  getHomeData()
  updateCountdown()
  window.addEventListener('resize', updateWindowWidth)
  countdownTimer = window.setInterval(updateCountdown, 1000)
})

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
  window.removeEventListener('resize', updateWindowWidth)
})
</script>

<style scoped>
.home {
  background: var(--bg-tertiary);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 轮播图 */
.banner-section {
  padding: 20px 0;
}

/* 节标题 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: var(--font-size-2xl);
  font-weight: var(--font-weight-bold);
  color: var(--text-primary);
}

/* 热门分类 */
.category-section {
  margin-bottom: 40px;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.category-item {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  overflow: hidden;
  cursor: pointer;
  transition: var(--transition-all);
  box-shadow: var(--shadow-card);
  border: 1px solid var(--border-primary);
}

.category-item:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-strong);
  border-color: var(--primary-color);
}

.category-image {
  height: 150px;
  overflow: hidden;
}

.category-image img {
  width: 100%;
  height: 100%;
  object-fit: fill;
  transition: transform 0.3s ease;
}

.category-item:hover .category-image img {
  transform: scale(1.05);
}

.category-info {
  padding: 16px;
}

.category-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  line-height: 1.4;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 2.8em;
}

/* 產品区域 */
.products-section {
  margin-bottom: 40px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

/* 產品卡片样式 */
.product-card {
  background: var(--bg-secondary);
  border-radius: var(--radius-xl);
  overflow: hidden;
  cursor: pointer;
  transition: var(--transition-all);
  box-shadow: var(--shadow-card);
  border: 1px solid var(--border-primary);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-strong);
  border-color: var(--primary-color);
}

.product-image {
  position: relative;
  padding-bottom: 75%;
  overflow: hidden;
}

.product-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: fill;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-tags {
  position: absolute;
  top: 8px;
  left: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-tag {
  padding: 4px 8px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
  color: white;
  line-height: 1.2;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.product-tag.hot {
  background: var(--gradient-danger);
}

.product-tag.popular {
  background: var(--gradient-warning);
}

.product-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  line-height: 1.4;
  overflow: hidden;
}

.product-meta {
  margin-top: auto;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.review-count {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
}

.product-sales {
  font-size: var(--font-size-xs);
  color: var(--text-muted);
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-top: 12px;
}

.current-price {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
  color: var(--primary-color);
}

/* 促销活动 */
.promotion-section {
  padding: 30px 0;
}

.countdown {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #666;
}

.countdown-time {
  display: flex;
  align-items: center;
  gap: 2px;
}

.time-item {
  background: var(--gradient-primary);
  color: var(--text-light);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-weight: var(--font-weight-bold);
  min-width: 24px;
  text-align: center;
}

.separator {
  color: #ff6900;
  font-weight: bold;
}

.promotion-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.promotion-item {
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  overflow: hidden;
  cursor: pointer;
  transition: var(--transition-all);
  box-shadow: var(--shadow-card);
  border: 1px solid var(--border-primary);
}

.promotion-item:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-strong);
  border-color: var(--primary-color);
}

.promo-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.promo-image img {
  width: 100%;
  height: 100%;
  object-fit: fill;
  transition: transform 0.3s ease;
}

.promotion-item:hover .promo-image img {
  transform: scale(1.05);
}

.promo-overlay {
  position: absolute;
  top: 10px;
  right: 10px;
}

.promo-price {
  gap: var(--spacing-xs);
  background: var(--gradient-primary);
  color: var(--text-light);
  padding: var(--spacing-xs) var(--spacing-md);
  border-radius: var(--radius-rounded);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-bold);
  box-shadow: var(--shadow-button);
}

.promo-info {
  padding: 16px;
}

.promo-title {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  line-height: 1.4;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 2.8em;
}

.promo-desc {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 随机產品列表样式 */
.random-products-list {
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.random-product-item {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  display: flex;
  gap: var(--spacing-lg);
  cursor: pointer;
  transition: var(--transition-all);
  border: 1px solid transparent;
}

.random-product-item:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-medium);
  transform: translateY(-2px);
}

.random-product-image {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
}

.random-product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.random-product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.random-product-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.random-product-meta {
  margin-bottom: 8px;
}

.random-product-rating {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.random-review-count {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
}

.random-product-sales {
  font-size: var(--font-size-xs);
  color: var(--text-muted);
}

.random-product-price {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.random-current-price {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  color: var(--primary-color);
}

.random-product-specs {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  background: var(--primary-bg);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
}

/* 响应式设计 */
@media (max-width: 1024px) {

  .category-grid,
  .products-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {

  .category-grid,
  .products-grid,
  .promotion-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .section-tabs {
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .category-grid,
  .products-grid,
  .promotion-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .random-products-list {
    margin-top: 16px;
    gap: 10px;
  }

  .random-product-item {
    padding: 10px;
    gap: 10px;
  }

  .random-product-image {
    width: 50px;
    height: 50px;
  }

  .random-product-name {
    font-size: 13px;
    margin-bottom: 4px;
  }

  .random-current-price {
    font-size: 14px;
  }

  .random-product-specs {
    font-size: 10px;
  }

  .random-review-count,
  .random-product-sales {
    font-size: 11px;
  }
}
</style>
